package cn.jdy.plugins.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.platform.entity.News;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.service.NewspService;

/**
 * @title 新闻信息控制类
 * @date 2014-03-12
 */
@Controller
@RequestMapping("/newsp")
public class NewspCtrl extends BaseCtrl {

	@Autowired
	private NewspService newsService;
	@Autowired
	private ConfService confService;
	//默认列表路径
	private static String viewName = "redirect:/newsp/list?s=";

	private News kwd;
	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(News entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/newspList.jsp");

		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "保存成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		mv.addObject("classList", confService.queryByType(GlobalConstant.TYPE_NEWS, 0L));
		User user = getUser();
		mv.addObject("userName", user.getUsername());
		return mv;
	}

	/**
	 * 异步查询
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(News news, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", newsService.query(news, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", newsService.count(news, fromDate, toDate));
			jsonMap.put("iTotalRecords", newsService.count());
			this.kwd = news;//keywords
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询新闻异常", e);
		}
		return jsonMap;
		
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null,null);
	}

	/**
	 * 编辑,将list中查询的参数entity传入
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id,News entity) {
		ModelAndView mv = new ModelAndView("/operate/newspDetail.jsp");
		mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_NEWS, 0L));
		News datas = this.newsService.find(id);
		News datanewsNews = new News();
		if(id==null){//add new one
			datanewsNews.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		}
		mv.addObject("data", id==null||id==0 ? datanewsNews : datas);
		User user = getUser();
		mv.addObject("username", user.getUsername());
//		mv.addObject("data", id==null||id==0 ? id : datas);
		return mv;
	}

	/**
	 * 保存时继续将查询的参数entity传入，保存成功时再查询一次
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(News news, Long pid,News entity) {
		ModelAndView mv = new ModelAndView();
		//将数组转化成String
		String[] ds=news.getDepartments();
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String deps = "";
		for(int i=0;i<46;i++){
			if(ds[i]==null || ds[i]=="")ds[i]=";";
			deps += ","+ds[i];
		}
		news.setDepars(deps);
		news.setDepartments(null);
		//
		try {
			//如果二级新闻类别为空，则使用一级类别
	      if(null == news.getColumnId()) {
	        news.setColumnId(pid);
	      }
			if(news.getId()==null) {// 新增文章
				//
				User user = getUser();
				news.setUserid(user.getId());
				if(null == news.getUsername() || news.getUsername()==""){
					news.setUsername(user.getUsername());      //update with daihu 确保文章的发布人一直是最开始的发布人员
				}
				//市局需要手动更改时间，如果为空则取正确时间
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				news.setTitle(news.getTitle().trim());
//				news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.newsService.save(news);
				jsonMap.put("statusCode", 100);
			} else {//更新文章
				User user = getUser();
				news.setUserid(user.getId());
				if(null == news.getUsername() || news.getUsername()==""){
					news.setUsername(user.getUsername());       //update with daihu 确保文章的发布人一直是最开始的发布人员
				}
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}//市局
				this.newsService.update(news);
				
				jsonMap.put("statusCode", 200);
				
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, news.getId());
			}
			// 清理栏目列表缓存
			NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			BaseLog.e(getClass(), "新闻保存异常！", e);
			jsonMap.put("statusCode", 400);
		}
		
		return jsonMap;
	}
	
	/**
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.newsService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
      NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除新闻异常！", e);
		}
		return mv;
	}
	
	/**
	 * 置顶/在原置顶基础上再次点击，即换为有效状态
	 * @param id
	 * @return
	 */
	@RequestMapping("/stickie/{id}")
	public ModelAndView reset(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/newspList.jsp");
			if(id!=null && id!=0){
				List<News> resultSet = this.newsService.queryStickieNews();
				int len = resultSet.size();
				News news = this.newsService.find(id);
				Long columnID = news.getColumnId();
				String crtStatus = news.getStatus();
				if(!crtStatus.equals("3")){
					int cnt=0;
					for(int i=0;i<len;i++){
						if(resultSet.get(i).getColumnId() == columnID) cnt++;
					}
					if(cnt==0){//保证一类新闻中只有一条新闻能被置顶
						news.setStatus("3");//置顶
					}
				}
				if(crtStatus.equals("3")){
					news.setStatus("1");//取消置顶，即换成有效状态
				}
				this.newsService.update(news);
			}
		return mv;
	}

	/**
	 * 市公安局
	 * 复签：只需要发布者一人签收
	 * 未复签时，签收状态为有效状态“1”
	 * @param id
	 * @param name
	 * @return
	 */
	@RequestMapping("/counterSign/{id}")
	public ModelAndView ctsigned(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/newspList.jsp");
		News data = this.newsService.find(id);
		if(name.equals(data.getUsername())){
			data.setStatus("4");//已复签
		}
		this.newsService.update(data);
		return mv;
	}
	
	/**
	 * 将当前条news设为
	 * 如果有效status=1，改成无效-status=8
	 * 如果无效-status=8，改成有效status=1
	 * @param news
	 * @param id
	 * @return
	 */
	@RequestMapping("/invNews/{id}")
	public ModelAndView invNews(News news,@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("redirect:/newsp/list");
		try {
			News data = this.newsService.find(id);
			if(data.getStatus().equals("1")){
				data.setStatus("8");
			}else if(data.getStatus().equals("8")){
				data.setStatus("1");
			}
			this.newsService.update(data);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "无效有效状态更改异常", e);
		}
		return mv;
	}
}
